(function($) {
    $.fn.disableTextSelect = function() {
		return this.each(function(){
			if($.browser.mozilla){//Firefox
				$(this).css('MozUserSelect','none');
			}else if($.browser.msie){//IE
				$(this).bind('selectstart',function(){return false;});
			}else{//Opera, etc.
				$(this).mousedown(function(){return false;});
			}
		});
	};	
    
	$.fn.logErrorAJAX = function(response) {
		var status = response.status;
		var statusText = response.statusText;
		var responseText = response.responseText;
		var response = status+'|'+statusText+'|'+responseText;
	
		var params = 'handler=logAJAXError&responseString='+response;
		Ext.Ajax.request({
	        url:    'ajaxDirector.php',
	        method: 'POST',
	        params: params
	    });
	};	
	/*
     * Options:
     *   elementClass:    which page elements are going to become message containers
     *   link:            true = button triggers the message box, false = the message box shows by default
     *   linkText:        text on the link button
     *   sendTo:          'individual' to send to only 1 person, 'input' to look for sendTo UID string in hidden field,
     *                         array to show checkboxes for many possible recipients
     *   sendToID:        int if only sending to 1 person, pipe delimited string of UID's if sending to several people (1|32|23)
     *   reply:           true if this message is a reply to another.
     *   from:            UID of person sending message
     *   fromType:        type of person sending message (team, client, owner???)
     *   fileAttach:      show file attachment button
     *   toClient:        true = include a checkbox for the client so we can sent a message to them
     *   clientID:        ID of the client to whom we're sending the message
     */
	$.fn.makeMessageBox = function(options) {
		var defaults = {
            elementClass:    'messageBoxContainer',
            link:            false,
			linkText:        commonTerms['send_message'],
			sendTo:          '',
			sendToID:        '',
			reply:           false,
			fromID:          '',
			fromType:        '',
			fileAttach:      false,
            toClient:        false,
            clientID:        ''
		};
        var options = $.extend(defaults, options);
        var obj = $(this);
        var container = $('.'+options.elementClass);
		$(container, obj).each(function() {       
               var element   = $(this);
               var elementID = element.attr('id');
               var itemType  = element.attr('itemType');

               if ($(this).data('buttonsAttached') != true) {
                   if (options.link == false) {
                        createMessageBox();
                   } else {

                        createLink();
                   }
                   $(this).data('buttonsAttached',true);
               }

               function createLink() {
                    var linkTextHTML = '<p id="messageBoxLinkContainer_'+elementID+'"><button class="smallButton" id="messageBoxLink_'+elementID+'"><span class="messages">'+options.linkText+'</span></button></p>';
                    element.after(linkTextHTML);
                    $('#messageBoxLink_'+elementID).click(function() {
                        $('#messageBoxLink_'+elementID).hide();
                        createMessageBox();
                        return false;
                    });
               }

               function createMessageBox() {
                    var messageBoxString = [];
                        messageBoxString.push('<div id="messageBoxContainer_'+elementID+'">');

                            messageBoxString.push('<div style="float: left; width: 410px;">');
                                messageBoxString.push('<p><textarea id="messageBox_'+elementID+'" class="messageBox expanding" style="color: #999;">'+options.linkText+'</textarea></p>');
                                messageBoxString.push('<div>'+createSendToElements()+'</div>');
                                messageBoxString.push('<div style="margin: 3px 0 0 4px;">');
                                    messageBoxString.push('<button id="submitMessage_'+elementID+'" class="smallButton" style="float: left; margin-right: 12px;"><span class="sendMessage">'+commonTerms['send']+'</span></button>');
                                    messageBoxString.push('<button id="cancelMessage_'+elementID+'" class="smallButton" style="float: left; margin-right: 12px;"><span class="cancel">'+commonTerms['cancel']+'</span></button>');
                                messageBoxString.push('</div>');
                            messageBoxString.push('</div><div style="float: left; margin: 6px 0 0 8px;">');
                                if (options.fileAttach == true) {
                                    messageBoxString.push('<button class="smallButton fileUploadButton" id="message_'+elementID+'" style="float: left;"><span class="upload">'+commonTerms['attachFiles']+'</span></button>');
                                    messageBoxString.push('<ul class="fileList" id="message_'+elementID+'_fileContainer"></ul></div>');
                                }
                            messageBoxString.push('</div>');
                            messageBoxString.push('<div style="clear: left; height: 6px;"></div>');
                    var messageBoxOutString = messageBoxString.join('');
                    element.after(messageBoxOutString);
                    $('textarea.expanding').elastic();
                    $('textarea.expanding').focus(function() {
                         $(this).val('').css('color','#333');
                     });
                     $('#submitMessage_'+elementID).click(function() {
                        saveMessage();
                     });
                     $('#cancelMessage_'+elementID).click(function() {
                        clearMessage();
                     });
                    if (options.reply == false) {
                        $('#sendTo_'+elementID+' .all').click(function() {
                            if ($('#sendTo_'+elementID+' .all').attr('checked',true)) {
                                $('#sendTo_'+elementID+' div.sendToCheckbox').attr('checked',true);
                            } else {
                                $('#sendTo_'+elementID+' div.sendToCheckbox').attr('checked',false);
                            }
                        });
                    }
                    genericFunctions.checkboxTrigger();
                    if (options.fileAttach == true) {
                        fileManagerObj.fileManagerButton();
                    }
               }
				
               function createSendToElements() {
                    var sendToString = '';
                    if (options.sendTo == 'individual') {
                        sendToString += '<input type="hidden" class="sendToCheckbox" recipType="individual" value="'+options.sendToID+'" />';
                    } else if (options.sendTo == 'input') {
                        var sendToIDList = element.find(':input').val();
                        sendToString += '<input type="checkbox" class="sendToCheckbox" value="'+sendToIDList+'" checked style="display: none;" />';
                    } else {
                        sendToString += '<p>'+commonTerms['send_message_to']+':</p>';
                        sendToString += '<div id="sendTo_'+elementID+'" style="width: 400px;">';
                        if (options.toClient == true) {
                            sendToString += '<p class="messageCheckboxContainer" style="margin: 0; padding: 0;"><input type="checkbox" class="sendToCheckbox" recipType="client" value="'+options.clientID+'" /> <span class="checkboxTrigger">'+commonTerms['client']+'</span></p>';
                        }
                        for(var a=0;a<=((sendToArray.length)-1);a++) {
                            sendToString += '<p class="messageCheckboxContainer" style="margin: 0; padding: 0;"><input type="checkbox" class="sendToCheckbox" recipType="team" value="'+sendToArray[a].UID+','+sendToArray[a].Language+'" /> <span class="checkboxTrigger">'+sendToArray[a].First_Name+' '+sendToArray[a].Last_Name+'</span></p>';
                        }
                        sendToString    += '</div>';
                    }
                    return sendToString;
               }
               
               function saveMessage() {
                    var itemID  = element.attr('itemID');
                    var message = $('#messageBox_'+elementID).val();

                    /*
                     * Creat our 'To' string
                     */
                    var toString = '', toType = '';
                    $('.sendToCheckbox').each(function() {
                        if ($(this).attr('checked') == true) {
                            toString += $(this).val()+'|';
                            toType   += $(this).attr('recipType')+'|';
                        }
                    });
                    /*
                     * Remove trailing |
                     */
                    toString = toString.slice(0, -1);
                    toType = toType.slice(0, -1);

                    /*
                     * Now save the message
                     */
                    var formHash = {
                                to       : toString,
                                toType   : toType,
                                message  : message,
                                itemType : itemType,
                                itemID   : itemID,
                                from     : options.fromID,
                                fromType : options.fromType
                    }
                    $.ajax({
                        type     : "POST",
                        url      : siteURL+'messaging/Messages/saveMessage',
                        data     : formHash,
                        dataType : 'json',
                        success: function(payload){
                            messagingObj.renderMessages(payload,'',element.next().next().attr('id'));
                        },
                        error: function (xhr, desc, exceptionobj) {
                            errorObj.ajaxError(xhr,desc,exceptionobj);
                        }
                    });

                    clearMessage();
               }

               function clearMessage() {
                   /*
                    * Now figure out if we need to display a new link
                    * or a new textbox
                    */
                    if (options.link == true) {
                         /*
                          * Show link
                          */
                         $('#messageBoxLink_'+elementID).show();
                         /*
                          * Remove message form container
                          */
                         $('#messageBoxContainer_'+elementID).remove();
                    }
               }
        });
          
	}
	
	$.fn.systemMessage = function(options) {
		var defaults = {
			noFade:  0,
			size:    'Small',
			message: ''
		};
		var options = $.extend(defaults, options);
		var obj = $(this);  
		
		if (options.status == 'error') {
			obj.html('<div id="statusDivInner" class="errorMessage'+options.size+'">'+options.message+'</div>');
			if (options.noFade != 1) {
				$('#statusDivInner').fadeOut(5000);
			}	
		} else if (options.status == 'success') {
			obj.html('<div id="statusDivInner" class="successMessage'+options.size+'">'+options.message+'</div>');
			if (options.noFade != 1) {
				$('#statusDivInner').fadeOut(5000);
			}	
		} else if (options.status == 'information') {
			obj.html('<div id="statusDivInner" class="infoMessage'+options.size+'">'+options.message+'</div>');
			if (options.noFade != 1) {
				$('#statusDivInner').fadeOut(5000);
			}
		} else if (options.status == 'wait') {
			obj.html('<div id="statusDivInner" class="activityMessage'+options.size+'">'+options.message+'</div>');
		} else if (options.status == 'waitFormField') {
			obj.addClass('formFieldWait');
		} else if (options.status == 'clearFormFieldStatus') {
			obj.removeClass('formFieldWait');
		} else if (options.status == 'clearStatus') {
			obj.html('');
		}	
		return obj;		
	};	
	
	$.fn.hiLiteCheckbox = function(options) {
		var defaults = {
			noFade: 0
		};
		var options = $.extend(defaults, options);
		var obj = $(this);  
	};	
	
	$.fn.createOptionsMenu = function(options) {
		var defaults = {
			editOption:   true,
			deleteOption: true,
			addOption:    true,
			printOption:  false,
			pdfOption:    false			
		};
		var options = $.extend(defaults, options);
		var obj = $(this);
		var menuString = '<ul>';
		if (options.editOption == true) {
			menuString += '<li class="iconEditSmall"><a href="#" class="editOption">'+commonTerms['edit']+'</a></li>';
		}
		if (options.deleteOption == true) {
			menuString += '<li class="iconDeleteSmall"><a href="#" class="deleteOption">'+commonTerms['delete']+'</a></li>';
		}
		if (options.addOption == true) {
			menuString += '<li class="iconNewSmall"><a href="#" class="addOption">'+commonTerms['add']+'</a></li>';
		}
		if (options.printOption == true) {
			menuString += '<li class="iconPrintSmall"><a href="#" class="printOption">'+commonTerms['print']+'</a></li>';
		}
		if (options.pdfOption == true) {
			menuString += '<li class="iconPDFSmall"><a href="#" class="pdfOption">'+commonTerms['pdf']+'</a></li>';
		}
		menuString    += '</ul>'; 
		obj.html(menuString);
	};

    $.fn.createContextMenu = function(options) {
        var defaults = {
            menuElement:   '',
            elementClass:  '',
            targetElement: ''
        }
        var options = $.extend(defaults, options);
        var menuHTML = $(options.menuElement).html();
        var obj = $(this);
        var target;

        if (options.targetElement == '') {
            target = obj.next();
        } else {
            target = $(options.targetElement);
        }
        var popdown_visibility = {
            "source" : false,
            "target" : false
        };
        obj.hover(function() {
            popdown_visibility["source"] = true;
            showPopdown(target);
        }, function(){
            popdown_visibility["source"] = false;
            hidePopdown(target,popdown_visibility);
        });
        target.hover(function(){
            popdown_visibility["target"] = true;
            showPopdown(target);
        }, function(){
            popdown_visibility["target"] = false;
            hidePopdown(target,popdown_visibility);
        });

        function showPopdown(target) {
            target.fadeIn(100);
        }

        function hidePopdown(target) {
            setTimeout(function() {
                if((popdown_visibility["source"] == false)&&(popdown_visibility["target"] == false)) {
                    target.hide();
                }
            },100);
        }
    }
	
	$.fn.hoverButtons = function(options) {
		var defaults = {
			addOption:        false,
			editOption:       true,
			deleteOption:     true,
            removeOption:     false,
            vCardRemoveOption:false,
			vCardOption:      false,
			pdfOption:        false,
			downloadOption:   false,
            archiveOption:    false,
            openOption:       false,
            viewOption:       false,
            addClass:         '',
            editClass:        '',
            deleteClass:      '',
            vCardRemoveClass: '',
            vCardClass:       '',
            pdfClass:         '',
            downloadClass:    '',
            removeClass:      '',
            archiveClass:     '',
            openClass:        '',
            viewClass:        '',
            removeClass:      '',

            elementClass:     '',
			position:         'topRight',
			insertion:        'prepend',
			insertionElement: '',
			width:            ''
		}
		var options = $.extend(defaults, options);
		var obj = $(this);		
		var container = $('.'+options.elementClass);
		
		var j=0;
		$(container, obj).each(function() {
            if ($(this).data('buttonsAttached') != true) {
                var itemID = $(this).attr('itemID');
                if (options.width != '') {
                    var width = 'width: '+options.width+';';
                }
                var buttonString  = '<ul id="controls'+itemID+'" style="display: none; '+width+'" class="smallButtonCluster '+options.position+'">';
                    if (options.addOption == true) {
                        buttonString += '<li class="'+options.addClass+'"><a href="#" class="buttonAdd" itemID="'+itemID+'" title="'+commonTerms['new']+'"><span class="add"></span></a></li>';
                    }
                    if (options.vCardOption == true) {
                        buttonString += '<li class="'+options.vCardClass+'"><a href="#" class="buttonVCard" itemID="'+itemID+'" title="'+commonTerms['vCard']+'"><span class="vcard"></span></a></li>';
                    }
                    if (options.vCardRemoveOption == true) {
                        buttonString += '<li class="'+options.vCardRemoveClass+'"><a href="#" class="buttonVCardRemove" itemID="'+itemID+'" title="'+commonTerms['remove']+'"><span class="vcardRemove"></span></a></li>';
                    }
                    if (options.pdfOption == true) {
                        buttonString += '<li class="'+options.pdfClass+'"><a href="#" class="buttonPDF" itemID="'+itemID+'" title="'+commonTerms['pdf']+'"><span class="pdf"></span></a></li>';
                    }
                    if (options.viewOption == true) {
                        buttonString += '<li class="'+options.viewClass+'"><a href="#" class="buttonView" itemID="'+itemID+'" title="'+commonTerms['view']+'"><span class="view"></span></a></li>';
                    }
                    if (options.archiveOption == true) {
                        buttonString += '<li class="'+options.archiveClass+'"><a href="#" class="buttonArchive" itemID="'+itemID+'" title="'+commonTerms['archive']+'"><span class="archive"></span></a></li>';
                    }
                    if (options.openOption == true) {
                        buttonString += '<li class="'+options.openClass+'"><a href="#" class="buttonOpen" itemID="'+itemID+'" title="'+commonTerms['open']+'"><span class="open"></span></a></li>';
                    }
                    if (options.editOption == true) {
                        buttonString += '<li class="'+options.editClass+'"><a href="#" class="buttonEdit" itemID="'+itemID+'" title="'+commonTerms['edit']+'"><span class="edit"></span></a></li>';
                    }
                    if (options.downloadOption == true) {
                        buttonString += '<li class="'+options.downloadClass+'"><a href="#" class="buttonDownload" itemID="'+itemID+'" title="'+commonTerms['download_file']+'"><span class="download"></span></a></li>';
                    }
                    if (options.deleteOption == true) {
                        buttonString += '<li class="'+options.deleteClass+'"><a href="#" class="buttonDelete" itemID="'+itemID+'" title="'+commonTerms['delete']+'"><span class="delete"></span></a></li>';
                    }
                    if (options.removeOption == true) {
                        buttonString += '<li class="'+options.removeClass+'"><a href="#" class="buttonRemove" itemID="'+itemID+'" title="'+commonTerms['remove']+'"><span class="remove"></span></a></li>';
                    }
                    buttonString += '<li class="blank"></li></ul>';

                var insertionElement = $(this);
                if (options.insertionElement != '') {
                    insertionElement = $('.'+options.insertionElement, this);
                }
				
                if (options.insertion == 'prepend') {
                    insertionElement.prepend(buttonString);
                } else if (options.insertion == 'append') {
                    insertionElement.append(buttonString);
                } else if (options.insertion == 'html') {
                    insertionElement.html(buttonString);
                }
                $(this).hover(
                    function() {
                        $('#controls'+itemID).show();
                    },
                    function() {
                        $('#controls'+itemID).hide();
                    }
                );
                $(this).data('buttonsAttached',true);
            }
		});	
	};
	
	$.fn.alternateTableRowColors = function() {
		var table = $(this);
		$('tbody tr:odd', table).removeClass('evenRow').addClass('oddRow');
		$('tbody tr:even', table).removeClass('oddRow').addClass('evenRow');	
		return table;
	}
	
	$.fn.alternateFormRowColors = function() {
		var form = $(this);
		$('p:even', form).addClass('altRow');	
		return form;
	}
	
	$.fn.alternateContainerRowColors = function() {
		var container = $(this);
		$('div.row:odd', container).addClass('oddRow');	
		return container;
	}
	
	$.fn.hiliteContainerRow = function() {
          var defaults = {
			hoverClass: 'hoverRow'
		}
		var options = $.extend(defaults, options);
		var container = $(this);
		$('div.row', container).hover(function() {
			$(this).addClass(options.hoverClass);
		}, function() {
			$(this).removeClass(options.hoverClass);
  		});
		return container;
	}
	
	$.fn.hiliteTableRow = function() {
		var table = $(this);
		$('tbody tr', table).hover(function() {
			$(this).addClass('hoverRow');
		}, function() {
			$(this).removeClass('hoverRow');
  		});
		return table;
	}
	
	$.fn.arrowThruList = function(options) {
		var defaults = {
			rowElement:    'li',
			activeElement: 'a'			
		};
		var options = $.extend(defaults, options);
		var listContainer = $(this);
		var selectedElement = 0;
		var totalElements = listContainer.children(options.rowElement).length;
		
		var startItem     = $(options.rowElement, listContainer).get(selectedElement);
		var startItemLink = $(options.rowElement+' '+options.activeElement, listContainer).get(selectedElement);
		$(startItem).addClass('liFocus');
		$(startItemLink).focus();
		
		$(options.rowElement+' '+options.activeElement, listContainer).each(function() {
			$(this).bind('keydown', function(e) {
				if (e.keyCode == 40) {
					var thisListItem     = $(options.rowElement, listContainer).get(selectedElement);
	            	if (selectedElement>0) {
	            		var prevListItem     = $(options.rowElement, listContainer).get(selectedElement-1);
	            		prevListItem.removeClass('liFocus');
	            	}      	
	            	
	            	var listItemLink = $(this).get(selectedElement);
					if (selectedElement == totalElements) {
	            		selectedElement = 0;
	            	}
	            	if (selectedElement)
	            	$(thisListItem).addClass('liFocus');
		            $(listItemLink).focus();
		            selectedElement++;
				} else if (e.keyCode == 38) {
					var nextListItem     = $(options.rowElement, listContainer).get(selectedElement+1);
	            	
				}
			});	
		});
	}
	
	$.fn.popupTableRow = function(options) {
		var defaults = {
			width:   '675px',
			colspan: 5,
			id:      0,
			content: ''
		};
		var options = $.extend(defaults, options);
		var table = $(this);
		var j=0;
		$('tbody tr', table).each(function(row) {
			$(this).click(function() {
				var clickedRow = $(this);
				
				/*
				 * Remove hover effect
				 */
				clickedRow.hover(function() {
					$(this).removeClass('hoverRow');
				},function(){
					$(this).removeClass('hoverRow');
				});
				
				clickedRow.addClass('rowClick');
								
				var rowContent = '<tr class="popupWindow" id="rowWindow_'+j+'">';
				rowContent    += '<td colspan="'+options.colspan+'">';
				rowContent    += '<div id="rowWindowContent_'+j+'" style="width: '+options.width+'">'+options.content+'<span class="close">CLOSE</span></div></td></tr>';
				
				clickedRow.after(rowContent);
				$('.close').click(function() {
					$('#rowWindow_'+j).remove();
					clickedRow.removeClass('rowClick');
					
					/*
					 * Replace hover effect
					 */
					clickedRow.hover(function() {
						$(this).addClass('hoverRow')
					}, function() {
						$(this).removeClass('hoverRow')
			  		});
				});
			});	
			j++;
  		});
		return table;
	}
	
	$.fn.tableSorter = function() {
		var $table = $(this)
		$('th', $table).each(function(column) {
			if ($(this).is('.sortable')) {
				$(this).addClass('clickable').hover(function() {
					$(this).addClass('sortHeaderHover')
				}, function() {
					$(this).removeClass('sortHeaderHover')
  				});
			}
			if ($(this).is('.sort-alpha')) {
				$(this).click(function() {
					if ($(this).attr('acdc') == '1') {
						var sortOrder = 0;
						$(this).attr('acdc','2');			
					} else {
						var sortOrder = 1;
						$(this).attr('acdc','1');
					}
					var rows = $table.find('tbody > tr').get();
  					rows.sort(function(a, b) {
  						var keyA = $(a).children('td').eq(column).text().toUpperCase();
  						var keyB = $(b).children('td').eq(column).text().toUpperCase();
  						if (sortOrder == 1) {
							if (keyA < keyB) return -1;
  							if (keyA > keyB) return 1;
  						} else {
  							if (keyA < keyB) return 1;
  							if (keyA > keyB) return -1;
  						}
  						return 0;
  					});
	      			$.each(rows, function(index, row) {
	      				$table.children('tbody').append(row);
	      			});	
	      			$table.alternateTableRowColors();
  				});
  			} else if ($(this).is('.sort-num')) {
				$(this).click(function() {
					if ($(this).attr('acdc') == '1') {
						var sortOrder = 0;
						$(this).attr('acdc','2');			
					} else {
						var sortOrder = 1;
						$(this).attr('acdc','1');
					}
					var rows = $table.find('tbody > tr').get();
  					rows.sort(function(a, b) {
						var keyA = parseFloat($(a).children('td').eq(column).text());
  						var keyB = parseFloat($(b).children('td').eq(column).text());
  						if (sortOrder == 1) {
  							if (keyA < keyB) return 1;
  							if (keyA > keyB) return -1;
  						} else {
  							if (keyA < keyB) return -1;
  							if (keyA > keyB) return 1;
  						}
  						return 0;
  					});
	      			$.each(rows, function(index, row) {
	      				$table.children('tbody').append(row);
	      			});
	      			$table.alternateTableRowColors();
  				});
			} else if ($(this).is('.sort-currency')) {
				$(this).click(function() {
					if ($(this).attr('acdc') == '1') {
						var sortOrder = 0;
						$(this).attr('acdc','2');			
					} else {
						var sortOrder = 1;
						$(this).attr('acdc','1');
					}
					var rows = $table.find('tbody > tr').get();
  					rows.sort(function(a, b) {
						var keyA = parseFloat($(a).children('td').eq(column).attr('currencySort'));
  						var keyB = parseFloat($(b).children('td').eq(column).attr('currencySort'));
  						if (sortOrder == 1) {
  							if (keyA < keyB) return 1;
  							if (keyA > keyB) return -1;
  						} else {
  							if (keyA < keyB) return -1;
  							if (keyA > keyB) return 1;
  						}
  						return 0;
  					});
	      			$.each(rows, function(index, row) {
	      				$table.children('tbody').append(row);
	      			});
	      			$table.alternateTableRowColors();
  				});
			} else if ($(this).is('.sort-date')) {
				var dateRE = /^(\d{2})[\/\- ](\d{2})[\/\- ](\d{4})/;
				$(this).click(function() {
					if ($(this).attr('acdc') == '1') {
						var sortOrder = 0;
						$(this).attr('acdc','2');			
					} else {
						var sortOrder = 1;
						$(this).attr('acdc','1');
					}
					var rows = $table.find('tbody > tr').get();
  					rows.sort(function(a, b) {
						var keyA = $(a).children('td').eq(column).attr('dateSort');
  						var keyB = $(b).children('td').eq(column).attr('dateSort');
  						keyA = keyA.replace(dateRE,"$3$1$2");
						keyB = keyB.replace(dateRE,"$3$1$2");
  						if (sortOrder == 1) {
  							if (keyA < keyB) return 1;
  							if (keyA > keyB) return -1;
  						} else {
  							if (keyA < keyB) return -1;
  							if (keyA > keyB) return 1;
  						}
  						return 0;
  					});
	      			$.each(rows, function(index, row) {
	      				$table.children('tbody').append(row);
	      			});
	      			$table.alternateTableRowColors();
  				});
			}				
  		});
  		return $table;
	}

	$.fn.formatCurrency = function(settings) {
		settings = jQuery.extend({
		    name: "formatCurrency",
		    useHtml: false,
			val:    '',
		    symbol: '$',
		    global: true
		}, settings);

		return this.each(function() {
		    var num = "0";
			if (settings.val>0) {
				num = settings.val;
			} else {
				num = $(this)[settings.useHtml ? 'html' : 'val']();
			}
		    num = num.replace(/\$|\,/g, '');
		    if (isNaN(num))
		        num = "0";
		    sign = (num == (num = Math.abs(num)));
		    num = Math.floor(num * 100 + 0.50000000001);
		    cents = num % 100;
		    num = Math.floor(num / 100).toString();
		    if (cents < 10)
		        cents = "0" + cents;
		    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
		        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));

		    $(this)[settings.useHtml ? 'html' : 'val'](((sign) ? '' : '-') + settings.symbol + num + '.' + cents);
		});
	};

	 // Remove all non numbers from text
	 $.fn.toNumber = function(settings) {
			settings = jQuery.extend({
				name: "toNumber",
				useHtml: false,
				global: true
			}, settings);

		return this.each(function() {
		  var method = settings.useHtml ? 'html' : 'val';
		  $(this)[method]($(this)[method]().replace(/[^\d\.]/g, ''));
		});
	 };

	 $.fn.makeCategoryEditBox = function(options) {
		 var defaults = {
			listJSON:     '',
			listType:     '',
			instanceName: '',
			siteArea:     '',
			selectID:     null
		};
		var options = $.extend(defaults, options);
		var obj = $(this);		
		var listJSON = options.listJSON;
		var listAPI = obj.qtip('api');
        
		loadListElements(listJSON);

		function loadListElements(listJSON) {
			if (typeof listJSON != 'object') {
				listJSON = eval(listJSON);
			}
			var listHTML = [];
			listHTML.push('<div style="height: 200px; overflow: auto;"><ul class="categoryList" listType="'+options.listType+'">');
			listHTML.push('<li><span class="icon_add_small"></span><input type="text" style="width: 180px;" value="'+commonTerms['add']+'" class="newCategory'+options.instanceName+'" /></li>');
			for(var a=0;a<listJSON.length;a++) {
                if (listJSON[a].ItemID>0) {
                    listHTML.push('<li itemID="'+listJSON[a].ItemID+'">');
                    listHTML.push('<a href="#" class="buttonDeleteSmall buttonDeleteCat'+options.instanceName+'"></a>');
                    listHTML.push('<span class="listContent'+options.instanceName+'">'+listJSON[a].ItemName+'</span>');
                    listHTML.push('<input type="text" style="display: none; width: 180px;" class="existingCategory'+options.instanceName+'" value="'+listJSON[a].ItemName+'" /></li>');
                }
            }
			listHTML.push('</ul></div>');
			var listHTMLString = listHTML.join('');			
			listAPI.updateContent(listHTMLString);
			attachEventHandlers();
		}

		function loadSelectElements(listJSON) {
			if (typeof listJSON != 'object') {
				listJSON = eval(listJSON);
			}
			var selectHTML = [];
			selectHTML.push('<option></option>');
			for(var a=0;a<listJSON.length;a++) {
				selectHTML.push('<option value="'+listJSON[a].ItemID+'">'+listJSON[a].ItemName+'</option>');
			}
			var selectHTMLString = selectHTML.join('');
			$('#'+options.selectID).html('').append(selectHTMLString);
		}

		/*
		 * Attach event handlers
		 */
		function attachEventHandlers() {
            $('.listContent'+options.instanceName).unbind('click').click(function() {
				$(this).hide();
				$(this).next().show().focus();
			});
			$('.buttonDeleteCat'+options.instanceName).unbind().click(function() {
				$(this).parent().fadeOut('fast');
				var itemID   = $(this).parent().attr('itemID');
				var itemType = $(this).parent().parent().attr('listType');
				deleteCategory(itemID,itemType,options.siteArea);
				return false;
			});

			$('ul.categoryList li input.existingCategory'+options.instanceName)
				.unbind('blur')
				.unbind('keyup')
				.blur(function() {
					var listContent = $(this).val();
					$(this).hide();
					$(this).prev().html(listContent).show();

					var itemID    = $(this).parent().attr('itemID');
					var itemType  = $(this).parent().parent().attr('listType');
					var itemValue = listContent;
					updateCategory(itemID,itemValue,itemType,options.siteArea);
				})
				.bind('keyup', function(e) {
					if (e.keyCode == 13) {
						var listContent = $(this).val();
						$(this).hide();
						$(this).prev().html(listContent).show();

						var itemID    = $(this).parent().attr('itemID');
						var itemType  = $(this).parent().parent().attr('listType');
						var itemValue = listContent;
						updateCategory(itemID,itemValue,itemType,options.siteArea);
					}
				});
                $('.newCategory'+options.instanceName)
                    .focus(function() {
                        $(this).val('');
                    })
                    .blur(function() {
                        var itemValue = $(this).val();
                        var itemType  = $(this).parent().parent().attr('listType');
                        addCategory(itemValue,itemType,options.siteArea);
                        $(this).val(commonTerms['add']);
                    })
                    .bind('keyup', function(e) {
                        if (e.keyCode == 13) {
                            var itemValue = $(this).val();
                            var itemType  = $(this).parent().parent().attr('listType');
                            addCategory(itemValue,itemType,options.siteArea);
                            $(this).val(commonTerms['add']);
                        }
                    });
        }

		function addCategory(itemValue,itemType,siteArea) {
            var formHash = {itemValue : itemValue}
			$.ajax({
				type:  "POST",
				url:   siteURL+'settings/SettingsCategories/newCategory/0/'+itemType+'/'+siteArea,
                data: formHash,
				success: function(payload,itemType){
					if (itemType == 'category') {
						categoryJSON = payload;
					} else if (itemType == 'tag') {
						tagJSON = payload;
					}
					loadListElements(payload);
					if (options.selectID != null) {
						loadSelectElements(payload);
					}
				},
				error: function (xhr, desc, exceptionobj) {
					errorObj.ajaxError(xhr,desc,exceptionobj);
				}
			});
		}
		function updateCategory(itemID,itemValue,itemType,siteArea) {
            var formHash = {itemValue : itemValue}
			$.ajax({
				type:  "POST",
				url:   siteURL+'settings/SettingsCategories/updateCategory/'+itemID+'/0/'+itemType+'/'+siteArea,
                data: formHash,
				success: function(payload,itemType){
					if (itemType == 'category') {
						categoryJSON = payload;
					} else if (itemType == 'tag') {
						tagJSON = payload;
					}
					if (options.selectID != null) {
						loadSelectElements(payload);
					}
				},
				error: function (xhr, desc, exceptionobj) {
					errorObj.ajaxError(xhr,desc,exceptionobj);
				}
			});
		}
		function deleteCategory(itemID,itemType,siteArea) {
			$.ajax({
				type:  "POST",
				url:   siteURL+'settings/SettingsCategories/deleteCategory/'+itemID+'/'+itemType+'/'+siteArea,
				success: function(payload){
					if (options.selectID != null) {
						loadSelectElements(payload);
					}
				},
				error: function (xhr, desc, exceptionobj) {
					errorObj.ajaxError(xhr,desc,exceptionobj);
				}
			});
		}
	 };

     $.fn.contentScroller = function(options) {
		var defaults = {
			interval: 5000
		};
        var options = $.extend(defaults, options);
        var obj = $(this);
        var currentHeadline = 0, oldHeadline = 0, headlineCount, headlineInterval;

        headlineCount = obj.find('.scrollerHeadline').size();
        obj.find('.scrollerHeadline').eq(currentHeadline).css('top','5px');
        headlineInterval = setInterval(contentRotate,options.interval);
        obj.hover(function() {
            clearInterval(headlineInterval);
        }, function() {
            headlineInterval = setInterval(contentRotate,5000);
            contentRotate();
        });

        function contentRotate() {
            currentHeadline = (oldHeadline + 1) % headlineCount;
            obj.find('.scrollerHeadline').eq(oldHeadline).animate({top: -205},"slow", function() {
                $(this).css('top', '210px');
            });
            obj.find('.scrollerHeadline').eq(currentHeadline).animate({top: 5},"slow");
            oldHeadline = currentHeadline;
        }
        
		return obj;
	};

    $.fn.liveDraggable = function (options) {
        this.live("mouseover", function() {
            if (!$(this).data("init")) {
                $(this).data("init", true).draggable(options);
            }
        });
    };

    $.fn.liveDroppable = function (options) {
        this.live("mouseover", function() {
            if (!$(this).data("init")) {
                $(this).data("init", true).droppable(options);
            }
        });
    };

})(jQuery);